
#include <bsp_i2c.h>

static I2C_HandleTypeDef sensor_i2c;

static void bsp_sensor_i2c_msp_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    /*##-1- Enable peripherals Clocks #################################*/
    /* Enable GPIO TX/RX clock */
    SENSOR_I2C_GPIO_RCC_EN();

    /* Enable USARTx clock */
    SENSOR_I2C_RCC_EN();

    /*##-2- Configure peripheral GPIO ##########################################*/
    /* UART RX GPIO pin configuration  */
    GPIO_InitStruct.Pin = SENSOR_I2C_SCL_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; /* Output drain */
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = SENSOR_I2C_AF;

    HAL_GPIO_Init(SENSOR_I2C_GROUP, &GPIO_InitStruct);

    /* SBUS connect to receiver pin configuration  */
    GPIO_InitStruct.Pin = SENSOR_I2C_SDA_PIN;
    GPIO_InitStruct.Alternate = SENSOR_I2C_AF;

    HAL_GPIO_Init(SENSOR_I2C_GROUP, &GPIO_InitStruct);
}

int bsp_sensor_i2c_init(void)
{
    bsp_sensor_i2c_msp_init();

    /* i2c init */
    sensor_i2c.Instance = SENSOR_I2C;
    sensor_i2c.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
    sensor_i2c.Init.ClockSpeed = SENSOR_I2C_CLK_SPEED;
    sensor_i2c.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
    sensor_i2c.Init.DutyCycle = I2C_DUTYCYCLE_2;
    sensor_i2c.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
    sensor_i2c.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
    sensor_i2c.Init.OwnAddress1 = SENSOR_I2C_MASTER_ADDR;
    sensor_i2c.Init.OwnAddress2 = 0x00;
    HAL_I2C_Init(&sensor_i2c);

    return 0;
}

I2C_HandleTypeDef* bsp_sensor_i2c_handle(void)
{
    return &sensor_i2c;
}
